﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Web;

namespace Common
{
    public class Client
    {
        private byte[] _byteBuffer;
        private const int BYTE_BUFFER_SIZE = 8192;
        private NetworkStream _networkStream;
        private TcpClient _client;

        public bool Connected
        {
            get { return this._client.Connected; }
        }

        public Client(string serverPath, int port)
        {
            try
            {
                IPAddress ipa = IPAddress.Parse(serverPath);
                _client = new TcpClient();
                _client.Connect(ipa, port);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }
            _byteBuffer = new byte[BYTE_BUFFER_SIZE];
            Console.WriteLine("Server Connected! Local:{0}-->Server:{1}", _client.Client.LocalEndPoint, _client.Client.RemoteEndPoint);
            _networkStream = _client.GetStream();
            _networkStream.BeginRead(_byteBuffer, 0, BYTE_BUFFER_SIZE, ReadAsyncCallback, this);
        }

        public void SendMessage(string msg)
        {
            var byteBuffer = Encoding.Unicode.GetBytes(msg);
            try
            {
                _networkStream.Write(byteBuffer, 0, byteBuffer.Length);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        public void ReadAsyncCallback(IAsyncResult ar)
        {
            int bytesRead = 0;
            try
            {
                bytesRead = _networkStream.EndRead(ar);
                if (bytesRead == 0)
                {
                    Console.WriteLine("Server offline");
                    return;
                }
                string msg = Encoding.Unicode.GetString(_byteBuffer, 0, bytesRead);
                Array.Clear(_byteBuffer, 0, _byteBuffer.Length);
                Console.WriteLine("Server Send Message : {0}", msg);
                //再次调用BeginRead(),完成自身调用，形成无限循环
                _networkStream.BeginRead(_byteBuffer, 0, BYTE_BUFFER_SIZE, ReadAsyncCallback, this);
            }
            catch (Exception ex)
            {
                if (_networkStream != null)
                    _networkStream.Dispose();
                _client.Close();
                Console.WriteLine(ex.Message);
            }
        }


    }
}